package com.bijava.util;

import com.bijava.entity.Column;
import com.bijava.entity.Table;
import com.bijava.entity.ConnectionEntity;
import com.bijava.entity.JdbcEntity;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JDBC的工具类，封装了jdbc的一些方法
 * @author lusong
 *
 */
public class JDBCUtils {


    public static void main(String[] args) {
        /*String jdbcUrl="jdbc:oracle:thin:@88.128.18.241:1521:orcl";
        String driverClass="oracle.jdbc.driver.OracleDriver";
        String user="bgdTest";
        String password="bgdTest";*/

        String jdbcUrl="jdbc:mysql://172.16.17.155:3306/gencode?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String driverClass="com.mysql.jdbc.Driver";
        String user="gencode";
        String password="gencode";

        ConnectionEntity connectionEntity = new ConnectionEntity(jdbcUrl,driverClass,user,password);

        TableFactory TableFactory = new TableFactory(connectionEntity);
        try {
            List<Table> list = TableFactory.getAllTables();
            for (Table table:list){
               List<Column> list2 = TableFactory.getColumn(table.getName() ,jdbcUrl);
                System.out.println(list2.toString());
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭jdbc的链接
    /**
     * 关闭statement和connection
     * @param ps
     * @param conn
     */
    public static void release(PreparedStatement ps, Connection conn){
        try {
            if(ps != null){
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try {
                if(conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void release(ResultSet result,PreparedStatement ps, Connection conn){
        try {
            if(result != null){
                result.close();
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }finally{
            try {
                if(ps != null){
                    ps.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                try {
                    if(conn != null){
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //获取jdbc的链接
    /**
     * 用于创建jdbc链接的工具类对象
     * @return
     */
    public static Connection getConnetions(ConnectionEntity connectionEntity) {
        Connection conn = null;
        try {
            //注册驱动程序
            Class.forName(connectionEntity.getDriverClass());
            //实际应该这样写(由于对应的应用程序中有一个对应的静态代码块，自动回将驱动的类对象进行驱动加载)
            //DriverManager.registerDriver((Driver) Class.forName(driverClass).newInstance());
            conn = DriverManager.getConnection(connectionEntity.getJdbcUrl(),connectionEntity.getUser(),connectionEntity.getPassword());
        }catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    public static List<Map<String,Object>> QueryForList(JdbcEntity jdbcEntity){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String,Object>> datas = null;
        try{
            conn = getConnetions(jdbcEntity);
            ps = conn.prepareStatement(jdbcEntity.getSql());
            rs = ps.executeQuery();

            ResultSetMetaData rsmd = rs.getMetaData();//元数据信息
            int count = rsmd.getColumnCount();//字段数量
            String[] colNames = new String[count];

            for(int i=1; i<=count; i++){
                colNames[i-1] = rsmd.getColumnName(i);//字段名称
            }
            datas = new ArrayList<Map<String,Object>>();
            while(rs.next()){
                Map<String, Object> item = new HashMap<String, Object>();
                for(int i=1;i<=count;i++){
                    item.put(colNames[i-1], rs.getObject(colNames[i-1]));
                }
                datas.add(item);
            }
        }catch(SQLException e){
            System.out.println(e.getMessage());
        }finally{
            JDBCUtils.release(ps, conn);
        }

        return datas;
    }
    public static Object QueryForOne(JdbcEntity jdbcEntity){
        List list=QueryForList(jdbcEntity);
        return list.size()>0?list.get(0):null;
    }

    public static int updateOrDelete(JdbcEntity jdbcEntity){
        Connection conn = null;
        PreparedStatement ps = null;
        int result=0;
        try {
            conn = JDBCUtils.getConnetions(jdbcEntity);
            ps = conn.prepareStatement(jdbcEntity.getSql());
            //用于增删改操作
            result= ps.executeUpdate();
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("出现异常1="+e.toString());
        }finally{
            JDBCUtils.release(ps, conn);
        }
        return result;
    }
    public static List<Map<String,Object>> QueryforListByOrcale(JdbcEntity jdbcEntity){
        jdbcEntity.setDriverClass("oracle.jdbc.driver.OracleDriver");
        return QueryForList(jdbcEntity);
    }
    public static List<Map<String,Object>> QueryforListByMysql(JdbcEntity jdbcEntity){
        jdbcEntity.setDriverClass("com.mysql.jdbc.Driver");
        return QueryForList(jdbcEntity);
    }

}